package servlet.personage;

import com.google.gson.Gson;
import data.Updata;
import filter.PersonagePort;
import servlet.Control;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "UpdataMessage",value = "/personage/updataMessage")
public class UpdataMessage extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id=request.getParameter("id");
        String name=request.getParameter("name");
        String msg=request.getParameter("msg");
        //如果发现用户篡改的越界行为，则不允许修改
        if(!validation(name,request)){
            return;
        }

        //修改城市
        if(name.equals("city")||name.equals("language")){
            Control.simpleSend(updataSelects(id,msg,name),response);
            return;
        }

        Control.simpleSend(Updata.changProfileMessage(id,name,msg),response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    //验证所修改的选项是否超越了页面权限,若没有返回true
    private static boolean validation(String name,HttpServletRequest request){
        if(name.contains("id")){
            return false;
        }else if(name.contains("priority")&&
                !PersonagePort.validationCookie(request,"ROOT","SID")){
            return false;
        }else if(name.contains("visit")){
            return false;
        }

        return true;
    }

    //修改城市或语言
    private static boolean updataSelects(String id,String msg,String name){
        List<String> introduces=new Gson().fromJson(msg,List.class);

        if(name.equals("city")){
            return Updata.changProfileCity(id,introduces);
        }else if (name.equals("language")){
            return Updata.changeProfileLanguage(id,introduces);
        }

        return false;
    }
}
